package com.example.webbrowser.Database;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.util.Log;
import com.example.webbrowser.Entity.MarkListView;


public class BookMarkManager {


    private static final String DEG_TAG ="webbrowser_FavroitesManager";

    private SQLManager database;
    private boolean flag = false;
    private List<MarkListView> resultMap;
    private  SQLiteDatabase sqLiteDatabase;

    public BookMarkManager(Context context){
        this.database =new SQLManager(context, "BooKMark", null, 1);
        this.sqLiteDatabase = database.getReadableDatabase();
        //Log.d(DEG_TAG,"成功");
    }

    public BookMarkManager() {

    }

    public boolean addFavorite(final String name,final String url) {
        flag = false;
        boolean ifmultiply =database.checkUrl(sqLiteDatabase, url);

        if(!ifmultiply){
            Log.d(DEG_TAG,"reason:未存在相同书签");
            flag = database.addMark(sqLiteDatabase, name, url);
        }else{
            Log.d(DEG_TAG,"reason:已经存在相同书签");
            flag = false;
        }
        Log.d(DEG_TAG,"result:"+flag);

        return flag;

    }


    public boolean deleteFavorite(String id) {
        flag = false;
        if(!Character.isDigit(id.charAt(0))){
            id = getId(id);
        }
        flag = database.deleteMark(sqLiteDatabase, id);
        updataDatabase(id);

        return flag;
    }

    public boolean deleteFavoriteByUrl(final String url) {
        flag = false;

        flag = database.deleteMarkByUrl(sqLiteDatabase, url);

        return flag;
    }


    public boolean modifyFavorite(final String id,final String name, final String url) {
        flag = false;
        flag = database.alterMark(sqLiteDatabase, id, name, url);

        return flag;
    }


    public List<MarkListView> getAllFavorites() {
        resultMap = new ArrayList<MarkListView>();
        resultMap = database.getAllMark(sqLiteDatabase);
        return resultMap;

    }
    public String getId(String url){
        return database.getId(sqLiteDatabase,url);
    }

    public boolean checkURL(String s){
        return database.checkUrl(sqLiteDatabase,s);
    }

    public void updataDatabase(String id){
        for (MarkListView i:getAllFavorites()) {
            if(Integer.valueOf(i.getId())>Integer.valueOf(id)){
                modifyFavorite(String.valueOf(Integer.valueOf(i.getId())),i.getName(),i.getUrl());
            }
        }
        showAllMark();
    }


    public void initMark(Context context){
        database.deleteData(sqLiteDatabase);
    }

    public void showAllMark(){
        for (MarkListView i: getAllFavorites()) {
            Log.d(DEG_TAG,i.toString());
        }
    }

}

